package com.ucode.application.controller.acis;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ucode.acis.mode.FamousExpert;
import com.ucode.acis.service.FamousExpertService;
import com.ucode.acis.service.WorksService;
import com.ucode.acis.vo.WorksVo;
import com.ucode.application.form.acis.FamousExpertForm;
import com.ucode.application.security.CurrentLoginUserService;
import com.ucode.application.vo.acis.FamousExpertVo;
import com.ucode.oss.model.FileInfo;
import com.ucode.oss.service.FileInfoService;
import com.ucode.springboot.starter.web.validator.group.AddGroup;
import com.ucode.springboot.starter.web.validator.group.UpdateGroup;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags="ACIS-名家")
@RestController
@RequestMapping("/acis-famousExpert")
@Validated
public class FamousExpertController {
    
    @Autowired
    private FamousExpertService famousExpertService;
    @Autowired
    private WorksService worksService;
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private CurrentLoginUserService currentLoginUserService;

    @PreAuthorize("hasAuthority('acis:famousExpert:list') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation("列表")
    @GetMapping(value = "/list")
    public ResponseResult<Object> list(
            @ApiParam(value ="姓名",required=false)  @RequestParam(value = "name",required=false) String name,
            @ApiParam(value ="别称",required=false)  @RequestParam(value = "nickname",required=false) String nickname,
            @ApiParam(value ="民族",required=false)  @RequestParam(value = "ethnic",required=false) String ethnic,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        Paginator<FamousExpert> paginator = famousExpertService.queryPage(name, nickname, ethnic, pageNum, pageSize);
//        Paginator<FamousExpertVo> vopag = new Paginator<>(paginator.getTotal(), paginator.getCurrentPage(), paginator.getRows());
//        if(paginator != null && CollUtil.isNotEmpty(paginator.getList())){
//            
//            List<Long> fileIds=  paginator.getList().stream().map(FamousExpert::getCoverId).collect(Collectors.toList());
//            List<FileInfo> files = fileInfoService.findByIds(fileIds);
//            Map<Long, FileInfo> fileMap = new HashMap<Long, FileInfo>();
//            if(CollUtil.isNotEmpty(files)){
//                fileMap = files.stream().collect(Collectors.toMap(FileInfo::getId,Function.identity(),(key1, key2) -> key1));
//            }
//            
//            List<FamousExpertVo> vos = new ArrayList<>();
//            for(FamousExpert famousExpert : paginator.getList()){
//                FileInfo coverFile = fileMap.get(famousExpert.getCoverId());
//                vos.add(new FamousExpertVo(famousExpert, coverFile));
//            }
//            vopag.setList(vos);
//        }
       
        return ResponseResult.success(paginator);
    }
    
    @PreAuthorize("hasAuthority('acis:famousExpert:edit') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="根据主键查询")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/getById/{id}")
    public ResponseResult<Object> getById(@PathVariable(name="id",required=true) Long id){
        
        FamousExpert famousExpert = famousExpertService.findById(id);
        
        if(famousExpert == null || famousExpert.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        
        FileInfo coverFile = fileInfoService.findById(famousExpert.getCoverId());
        return ResponseResult.success(new FamousExpertVo(famousExpert, coverFile));
    }
    
    @PreAuthorize("hasAuthority('acis:famousExpert:detail') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="详情信息")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/detail/{id}")
    public ResponseResult<Object> detail(@PathVariable(name="id",required=true) Long id){
        
        FamousExpert famousExpert = famousExpertService.findById(id);
        if(famousExpert == null || famousExpert.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        FileInfo coverFile = fileInfoService.findById(famousExpert.getCoverId());
        return ResponseResult.success(new FamousExpertVo(famousExpert, coverFile));
    }
    
    @PreAuthorize("hasAuthority('acis:famousExpert:detail') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation("名家作品列表")
    @GetMapping(value = "/works")
    public ResponseResult<Object> works(
            @ApiParam(value ="名家Id",required=false)  @RequestParam(value = "famousId",required=true) Long famousId,
            @ApiParam(value ="作品名称",required=false)  @RequestParam(value = "name",required=false) String name,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        Paginator<WorksVo> paginator = worksService.queryPage(name, famousId, pageNum, pageSize);
        return ResponseResult.success(paginator);
    }
    
    @PreAuthorize("hasAuthority('acis:famousExpert:edit') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="创建")
    @PostMapping("/create")
    public ResponseResult<Object> create(@Validated({AddGroup.class}) @RequestBody FamousExpertForm form) {
        
        FamousExpert famousExpert = form.build();
        int i = famousExpertService.insert(famousExpert);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('acis:famousExpert:edit') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="更新")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/update/{id}")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
            @Validated({UpdateGroup.class}) @RequestBody FamousExpertForm form) {
        
        FamousExpert famousExpert = form.build();
        famousExpert.setId(id);
        int i = famousExpertService.update(famousExpert);
        
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('acis:famousExpert:delete') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="删除")
    @PostMapping("/delete")
    public ResponseResult<Object> delete(
            @ApiParam(value="Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        famousExpertService.delete(ids);
        return ResponseResult.success();
    }
    
}
